import Mock from 'mockjs'
import data from './interface/data'
import user from './interface/user'

import { parseUrl } from './utils'

const mocks = [
  ...data,
  ...user
]

// 初始化mock
// https://expressjs.com/en/4x/api.html#req
function mockInit() {
  function XHR2ExpressReqWrap(respond) {
    return function (options) {
      let result = null
      if (respond instanceof Function) {
        const { body, type, url } = options
        result = respond({
          method: type,
          body: JSON.parse(body),
          query: parseUrl(url)
        })
      } else {
        result = respond
      }
      return Mock.mock(result)
    }
  }

  for (let i of mocks) {
    Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  }
}

export default mockInit
